"""数据库连接配置"""
from redis import Redis
from neo4j import GraphDatabase
from typing import Optional
from app.core.config import settings


class RedisClient:
    """Redis客户端"""
    _instance: Optional[Redis] = None
    
    @classmethod
    def get_client(cls) -> Redis:
        """获取Redis客户端实例"""
        if cls._instance is None:
            try:
                cls._instance = Redis(
                    host=settings.REDIS_HOST,
                    port=settings.REDIS_PORT,
                    db=settings.REDIS_DB,
                    decode_responses=True,
                    socket_connect_timeout=1,  # 1秒连接超时（快速失败）
                    socket_timeout=2,  # 2秒操作超时（快速失败）
                    retry_on_timeout=False,  # 不重试，快速失败
                    health_check_interval=30
                )
                # 快速ping测试（如果Redis不可用会快速失败）
                cls._instance.ping()
            except Exception as e:
                # 如果连接失败，抛出异常，让调用方处理
                print(f"警告: Redis连接失败: {e}")
                cls._instance = None
                raise
        return cls._instance
    
    @classmethod
    def close(cls):
        """关闭Redis连接"""
        if cls._instance:
            cls._instance.close()
            cls._instance = None


class Neo4jClient:
    """Neo4j客户端"""
    _driver = None
    
    @classmethod
    def get_driver(cls):
        """获取Neo4j驱动实例（延迟初始化，不阻塞）"""
        if cls._driver is None:
            try:
                cls._driver = GraphDatabase.driver(
                    settings.NEO4J_URI,
                    auth=(settings.NEO4J_USER, settings.NEO4J_PASSWORD),
                    connection_timeout=2  # 2秒连接超时
                )
            except Exception as e:
                print(f"⚠️ Neo4j驱动创建失败: {e}")
                return None
        return cls._driver
    
    @classmethod
    def get_session(cls):
        """获取Neo4j会话"""
        driver = cls.get_driver()
        return driver.session()
    
    @classmethod
    def close(cls):
        """关闭Neo4j驱动"""
        if cls._driver:
            cls._driver.close()
            cls._driver = None


# 启动时初始化，关闭时清理
def init_db():
    """初始化数据库连接（非阻塞）"""
    # Redis连接测试（快速失败，不阻塞）
    try:
        redis_client = RedisClient.get_client()
        redis_client.ping()
        print("✓ Redis连接成功")
    except Exception as e:
        print(f"⚠️ Redis连接失败（将使用内存存储）: {e}")
    
    # Neo4j连接测试（可选，不阻塞启动，快速失败）
    try:
        driver = Neo4jClient.get_driver()
        if driver:
            driver.verify_connectivity()
            print("✓ Neo4j连接成功")
        else:
            print("⚠️ Neo4j驱动未创建（部分功能可能不可用）")
    except Exception as e:
        print(f"⚠️ Neo4j连接失败（部分功能可能不可用）: {e}")


def close_db():
    """关闭数据库连接"""
    RedisClient.close()
    Neo4jClient.close()

